import router from '@ohos.router';
import prompt from '@ohos.prompt';
import ajax from '../../http/http';
import data_storage from '@ohos.data.storage';


export default {
    data: {
        title: "",
        user: {
            username: '',
            password: ''
        }
    },
    onInit() {
        this.title = this.$t('strings.world');
    },
    usernameChange(event) {
        this.user.username = event.value;
    },
    passwordChange(event) {
        this.user.password = event.value;
    },
    login() {
        // 根据个人情况，可添加一些数据正确性校验代码
        if (this.user.username == '') {
            prompt.showToast({
                message: '请输入正确的手机号码'
            });
        } else if (this.user.password == '') {
            prompt.showToast({
                message: '请输入密码'
            });
        } else {
            console.info('Form data is : ' + JSON.stringify(this.user));
            ajax.post('/login', this.user, (result) => {
                if (result.code == 20000) {
                    console.info('Login Success Token:' + result.data.token);
                    // 以下是将数据存储到APP缓存中
                    this.$app.$def.globalData.user = result.data.user;
                    this.$app.$def.globalData.token = result.data.token;

                    // 以下是将数据存储到数据库中
                    let storage = data_storage.getStorageSync(this.$app.$def.globalData.path);
                    storage.putSync('token', result.data.token);
                    storage.putSync('user', JSON.stringify(result.data.user));
                    storage.flushSync();

                    // 成功后跳转首页
                    router.push({
                        url: 'pages/index/index'
                    });
                } else {
                    prompt.showToast({
                        message: result.msg
                    });
                }
            });
        }
    },
    resetPwd() {
        router.push({
            url: 'pages/resetPwd/resetPwd'
        })
    },
    registered() {
        router.push({
            url: 'pages/register/register'
        })
    }
}



